package com.my.lucky.ui;

import javax.swing.*;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

public class SwingLogHandler extends Handler {
    private final JTextArea textArea;
    private final int maxLines;

    public SwingLogHandler(JTextArea textArea, int maxLines) {
        this.textArea = textArea;
        this.maxLines = maxLines;
    }

    @Override
    public void publish(LogRecord record) {
        if (record == null || textArea == null) return;

        SwingUtilities.invokeLater(() -> {
            try {
                String message = getFormatter().format(record);
                textArea.append(message);

                // 限制最大行数
                String text = textArea.getText();
                String[] lines = text.split("\n");
                if (lines.length > maxLines) {
                    StringBuilder newText = new StringBuilder();
                    for (int i = lines.length - maxLines; i < lines.length; i++) {
                        newText.append(lines[i]).append("\n");
                    }
                    textArea.setText(newText.toString());
                }

                // 自动滚动到底部
                textArea.setCaretPosition(textArea.getDocument().getLength());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void flush() {
        // 不需要实现
    }

    @Override
    public void close() throws SecurityException {
        // 不需要实现
    }
} 